const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-session')
// const session = require('koa-session2')

const blog = require('./routes/blog')
const user = require('./routes/user')

// error handler
onerror(app)

// session

// app.use(
//   session({
//     key: 'HAIYANG' //default "koa:sess"
//   })
// )

app.keys = ['blog']

const CONFIG = {
  key: 'koa:sess',
  maxAge: 24 * 60 * 60 * 1000,
  autoCommit: true,
  overwrite: true,
  httpOnly: true,
  signed: true,
  rolling: false,
  renew: false
}
app.use(session(CONFIG, app))

// middlewares
// post 数据解析
app.use(
  bodyparser({
    enableTypes: ['json', 'form', 'text']
  })
)
// 解析json
app.use(json())
app.use(logger())
// app.use(require('koa-static')(__dirname + '/public'))

// app.use(views(__dirname + '/views', {
//   extension: 'pug'
// }))

// logger log日志
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes 路由
app.use(blog.routes(), blog.allowedMethods())
app.use(user.routes(), user.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
